/*
 * RepeatInstruction.java
 * 
 * last update: 24.01.2010 by Olaru Victor
 * 
 * author:	Victor(victor.olaru@gmail.com)
 * 
 * Obs:
 */

package engine;

@SuppressWarnings("serial")
class RepeatInstruction extends DefaultInstruction{
	Expression e;
	DefaultInstruction body;

	RepeatInstruction(NameSpace ns, int db, InstructionDescription desc,
			Expression e, DefaultInstruction body,
			DefaultInstruction next)
			{
		super(ns, db, desc);
		this.e = e;
		this.body = body;
		if (body != null)
			body.append(this);
		add(next);
		state = -1;
			}

	public Instruction next() {
		if (state <= 0) {
			state = -1;
			return next;
		}
		return body;
	}

	// self-explanatory
	public void execute()
	throws InterpretTimeException, SimulationStoppedException
	{
		if (state == -1) {
			waitToRun();
			xConsole.trace(toString() + "->");
			try {
				state = (int) e.evaluate().getLong();
			} catch (InterpretTimeException intex) {
				throw new InterpretTimeException(toString() + ": error: " + intex);
			}
			if (body == null) state = -1;
		} else state --;
	}
}
